<?php
/**
 * Description of GDImage
 *
 * @author lyb
 */
class GDImage {
    public static $imgTypes=array(
        1 =>"GIF",
        2 =>"JPG",
        3 =>"PNG",
        4 =>"SWF",
        5 =>"PSD",
        6 =>"BMP",
        7 =>"TIFF(intel byte order)",
        8 =>"TIFF(motorola byte order)",
        9 =>"JPC",
        10 =>"JP2",
        11 =>"JPX",
        12 =>"JB2",
        13 =>"SWC",
        14 =>"IFF",
        15 =>"WBMP",
        16 =>"XBM");
    protected $imgRC;
    protected $info;
    protected function __construct() {
        
    }
    
    public static function fromFile($fileName){
        $info=self::getImgInfo($fileName);
        if(!$info){
            return FALSE;
        }
        $rc=null;
        switch ($info["type"]){
            case "GIF":
                $rc=imagecreatefromgif($fileName);
                break;
            case "JPG":
                $rc=imagecreatefromjpeg($fileName);
                break;
            case "PNG":
                $rc=imagecreatefrompng($fileName);
                break;
            default :
                return FALSE;
        }
        $img=new GDImage();
        $img->setImgResource($rc);
        return $img;
    }
    protected function setImgResource($rc){
        $this->imgRC=$rc;
    }
    protected static function create($width,$height){
        $rc=imagecreatetruecolor($width, $height);
        $img=new GDImage();
        $img->setImgResource($rc);
        return $img;
    }


    public static function getImgInfo($fileName){
        $size=@getimagesize($fileName);
        if($size==FALSE){
            return FALSE;
        }
        $info=array(
            "width"=>$size[0],
            "height"=>$size[1],
            "type"=> self::$imgTypes[$size[2]],
            "mime"=>$size["mime"]);
        return $info;
    }
    
    public function jpeg($fileName=NULL,$quality=80){
        imagejpeg($this->imgRC,$fileName,$quality);
    }
    public function png($fileName=null ){
        imagepng($this->imgRC,$fileName);
    }
    public function gif($fileName=null){
        imagegif($this->imgRC,$fileName);
    }
}
